﻿#include "EditorDebugAndRunAbilityGroupModel.h"

#include "Output/Console.h"

#include "Framework/Editor.h"

#include "Ability/Variable/EditorVariableAbilityModel.h"
#include "Ability/CallStack/EditorCallStackAbilityModel.h"
#include "Ability/Breakpoint/EditorBreakpointAbilityModel.h"

#include "Project/ProjectModel.h"

void REditorDebugAndRunAbilityGroupModel::FirstTimeInitializeObject()
{
    Super::FirstTimeInitializeObject();

    auto Variable=NewObject<REditorVariableAbilityModel>(this);
    Variable->SetDebugModel(this);
    Variable->bIsExpanded=true;
    Abilities.Add(Variable);

    auto CallStack=NewObject<REditorCallStackAbilityModel>(this);
    CallStack->SetDebugModel(this);
    CallStack->bIsExpanded=true;
    Abilities.Add(CallStack);

    auto Breakpoint=NewObject<REditorBreakpointAbilityModel>(this);
    Breakpoint->SetDebugModel(this);
    Breakpoint->bIsExpanded=true;
    Abilities.Add(Breakpoint);    

    UpdateLayout();
}

EDebugClientState REditorDebugAndRunAbilityGroupModel::GetClientState() const
{
    auto Debugger=REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>();
    return Debugger->GetClientState();
}

void REditorDebugAndRunAbilityGroupModel::Launch()
{
    auto Debugger=REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>();
    
    switch(DebugConfiguration)
    {
        case EDebugConfiguration::AttachToProject:
        Debugger->AttachTo(DefaultPort);
        return;

        case EDebugConfiguration::Project:
        {
            //1.build the project
            if(!Compile())
            {
                return;
            }
            //2.launch
            Debugger->Launch(DefaultPort);
            return;
        }
    }


}

void REditorDebugAndRunAbilityGroupModel::Pause()
{
    auto Debugger=REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>();
    Debugger->Pause();
}

void REditorDebugAndRunAbilityGroupModel::Continue()
{
    auto Debugger=REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>();
    Debugger->Continue();    
}

void REditorDebugAndRunAbilityGroupModel::Stop()
{
    auto Debugger=REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>();
    Debugger->Stop(); 
}

bool REditorDebugAndRunAbilityGroupModel::Compile()
{
    RProjectModelPtr ProjectManager=REditor::Get()->GetSubsystem<RProjectModel>();

    auto Error=ProjectManager->BuildProject();
    if(Error.HasValue())
    {
        WH::PrintLine(U"编译失败");
        WH::PrintLine(Error.GetValue());
        return false;
    }
    else
    {
        WH::PrintLine(U"编译成功");
        return true;
    }
}
